<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Transaksi extends CI_Controller {

	public function __construct()
	{
	   parent::__construct();
			$this->CI=& get_instance();
			$this->load->helper('flexigrid');
			$this->load->library('flexigrid');
			$this->load->library('session');
			$this->load->model('akun_model');
			$this->load->model('batch_model');
			$this->load->model('transaksi_akun_model');
			$this->load->model('transaksi_keuangan_model');
	}


	//load Grid
    function index() {
        $id_batch = $this->input->post('batch');
        if ($id_batch == null) {
            if ($this->session->userdata('id_batch') == null) {
                $id_batch = 0;
            } else {
                $id_batch = $this->session->userdata('id_batch');
            }
        }
        $this->loadDataGrid($id_batch);
    }

    public function loadDataGrid($id_batch){
		$colModel['no'] = array('No', 30, TRUE, 'center', 0);
        $colModel['Tanggal_Transaksi'] = array('Tanggal Transaksi', 120, TRUE, 'center', 1);
        $colModel['No_Bukti'] = array('Nomer Bukti', 100, TRUE, 'center', 1);
        $colModel['Keterangan'] = array('Keterangan', 250, TRUE, 'center', 0);
        $colModel['Batch'] = array('Batch', 120, TRUE, 'center', 1);
		$colModel['Jumlah_Transaksi'] = array('Jumlah Saldo', 100, TRUE, 'center', 0);
		$colModel['edit'] = array('Edit', 50, TRUE, 'center', 0);
		
		 $gridParams = array(
            'width' => 'auto',
            'height' => 300,
            'rp' => 10,
            'rpOptions' => '[5,10,15,20,25,40]',
            'pagestat' => 'Menampilkan: {from} hingga {to} dari {total} data.',
            'blockOpacity' => 0.5,
            'title' => 'Daftar Transaksi',
            'showTableToggleBtn' => true
        );
		
		
		
		$buttons[] = array('Tambah', 'add', 'spt_js');
        $buttons[] = array('separator');
        $buttons[] = array('Hapus', 'delete', 'spt_js');

        // mengambil data dari file controler ajax pada method grid_berkas
        $grid_js = build_grid_js('flex1', site_url("keuangan/transaksi/grid_transaksi/".$id_batch), $colModel, 'No_Bukti', 'asc', $gridParams, $buttons);
	
	
		$data['added_js'] =
                "<script type='text/javascript'>
		function spt_js(com,grid)
		{
			if (com=='Tambah')
			{
				location.href='" . base_url() . "index.php/keuangan/transaksi/tambah_transaksi'; 
			}
			
			if (com=='Hapus')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin menghapus ' + $('.trSelected',grid).length + ' data transaksi?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '" . base_url() . "index.php/keuangan/transaksi/delete" . "',
							   data: 'items='+itemlist,
							   success: function(data){
								$('#flex1').flexReload();
							   }
							});
						}
					} else {
						return false;
					} 
				}
				
		} 
		</script>
		";
        
		//'<a href=\''.base_url().'index.php/peserta/peserta/status/'.$row->ID_PESERTA.'\'>'.$status.'</a> ',
        //additional JS
        
		
		
		
		$data_grid['js_grid'] = $grid_js;
		$data['id_batch'] = $id_batch;
		$data['batch'] = $this->batch_model->get_batch($this->session->userdata('id_lisensi'));
        
        //rendering view
        $data['title'] = 'Daftar Transaksi';
        $this->template->write_view('header', 'template/header', $data);
        $this->template->write_view('content', 'keuangan/grid_transaksi', $data_grid);
        $this->template->write_view('footer', 'template/footer', $data);
        $this->template->render();
		
	}
	
	function grid_transaksi($id_batch) {
        $valid_fields = array('Tanggal_Transaksi', 'No_Bukti', 'Jumlah_Transaksi');
        $this->flexigrid->validate_post('No_Bukti', 'asc', $valid_fields);
        $records = $this->transaksi_keuangan_model->get_data_transaksi($id_batch);
        $this->output->set_header($this->config->item('json_header'));

        $no = 0;
        foreach ($records['records']->result() as $row) {
		
		// $status = '';
		// if ($row->ID_TRANSAKSI == NULL) {
			// $status = '<img border=\'0\' src=\'' . base_url() . 'images/grid/edit.png\'>';
		// } else {
			$status = '<img border=\'0\' src=\'' . base_url() . 'images/grid/edit.png\'>';
		//}
		
			$record_items[] = array(
				$row->ID_TRANSAKSI,
				$no = $no + 1,
				$row->TANGGAL_TRANSAKSI,
				$row->NO_BUKTI,
				$row->KETERANGAN,
				$row->NAMA_BATCH,
				'Rp. '. number_format($row->JUMLAH_TRANSAKSI, null, ',', '.'). ',-',
				'<a href=\'' . base_url() . 'index.php/keuangan/transaksi/edit_transaksi/' . $row->ID_TRANSAKSI . '\'>' . $status . '</a> '
			);
		}
		 if (isset($record_items))
            $this->output->set_output($this->flexigrid->json_build($records['record_count'], $record_items));
        else
            $this->output->set_output('{"page":"1","total":"0","rows":[]}');
	}
	
	public function tambah_transaksi()
	{
		$data['title'] = 'Tambah Transaksi';
                $data['post_action'] = 'keuangan/transaksi/insert_transaksi';

                $akun = $this->akun_model->get_active_akun();
                $options[0] = '-- Pilih Akun --';
                foreach ($akun->result() as $row){
                    $options[$row->ID_AKUN] = $row->NAMA_AKUN;
                }
                $data['akun'] = $options;
				
				//dropdown batch
				unset($options);
				$batch = $this->batch_model->get_batch($this->session->userdata('id_lisensi'));
                $options[0] = '-- Pilih Batch --';
                foreach ($batch->result() as $row){
                    $options[$row->ID_BATCH] = $row->NAMA_BATCH;
                }
                $data['batch'] = $options;

		$this->template->write_view('header', 'template/header',$data);
		$this->template->write_view('content', 'keuangan/tambah_transaksi',$data);
		$this->template->write_view('footer', 'template/footer',$data);
		$this->template->render();
	}

        // fungsi untuk insert data transaksi ke dalam database
        public function insert_transaksi(){
            if (!$this->cek_validasi()){
                $this->tambah_transaksi();
            }else{
                $tgl = $this->input->post('yy_transaksi').'-'.$this->input->post('mm_transaksi').'-'.$this->input->post('dd_transaksi');
                $keterangan = $this->input->post('keterangan');
                $id_batch = $this->input->post('id_batch');

                // insert data transaksi keuangan
                $transaksi = $this->transaksi_keuangan_model->getLast_noBukti();
                if ($transaksi->num_rows() > 0)
                        $no_bukti = $transaksi->row()->NO_BUKTI+1;
                else $no_bukti = 1000;

                $data = array('NO_BUKTI'=>$no_bukti,'ID_BATCH'=>$id_batch,
                    'KETERANGAN'=>$keterangan,'TANGGAL_TRANSAKSI'=>$tgl);

                $this->transaksi_keuangan_model->tambah_transaksi_keuangan($data);
                $id_transaksi = $this->transaksi_keuangan_model->getLast_transaksi_keuangan($no_bukti)->row()->ID_TRANSAKSI;

                // insert data transaksi akun
                for ($i=0; $i<=1; $i++){
                    if ($i == 0){
                        $akun = $this->input->post('akun_debet');
                        $jumlah = $this->input->post('jml_debet');
                    }else{
                        $akun = $this->input->post('akun_kredit');
                        $jumlah = $this->input->post('jml_kredit');
                    }

                    for ($j=0; $j<count($akun); $j++){
                        $data = array('ID_AKUN'=>$akun[$j],'ID_TRANSAKSI'=>$id_transaksi,
                            'JUMLAH_TRANSAKSI'=>$jumlah[$j],'STATUS_NOTE'=>$i);

                        $this->transaksi_akun_model->tambah_transaksi_akun($data);
                    }
                }

                redirect('keuangan/transaksi');
            }
        }
	
	public function edit_transaksi($id_transaksi)
	{
		$data['title'] = 'Edit Transaksi';
                $data['post_action'] = 'keuangan/transaksi/update_transaksi/'.$id_transaksi;

                $akun = $this->akun_model->get_active_akun();
                $options[0] = '-- Pilih Akun --';
                foreach ($akun->result() as $row){
                    $options[$row->ID_AKUN] = $row->NAMA_AKUN;
                }
                $data['akun'] = $options;

                $transaksi = $this->transaksi_keuangan_model->get_transaksi_keuangan_byID($id_transaksi);
                $debet = $this->transaksi_akun_model->get_transaksi_byStatus($id_transaksi, 0);
                $kredit = $this->transaksi_akun_model->get_transaksi_byStatus($id_transaksi, 1);

                $data['transaksi'] = $transaksi->result();
                $data['debet'] = $debet->result();
                $data['kredit'] = $kredit->result();

		$this->template->write_view('header', 'template/header',$data);
		$this->template->write_view('content', 'keuangan/edit_transaksi',$data);
		$this->template->write_view('footer', 'template/footer',$data);
		$this->template->render();
	}

        public function update_transaksi($id_transaksi){
            if (!$this->cek_validasi()){
                $this->edit_transaksi($id_transaksi);
            }else{
                $tgl = $this->input->post('yy_transaksi').'-'.$this->input->post('mm_transaksi').'-'.$this->input->post('dd_transaksi');
                $keterangan = $this->input->post('keterangan');

                // update data transaksi keuangan
                $data = array('KETERANGAN'=>$keterangan,'TANGGAL_TRANSAKSI'=>$tgl);

                $this->transaksi_keuangan_model->ubah_transaksi_keuangan($data, $id_transaksi);

                // update data transaksi akun
                for ($i=0; $i<=1; $i++){
                    if ($i == 0){
                        $akun = $this->input->post('akun_debet');
                        $jumlah = $this->input->post('jml_debet');
                    }else{
                        $akun = $this->input->post('akun_kredit');
                        $jumlah = $this->input->post('jml_kredit');
                    }
                    $this->transaksi_akun_model->hapus_transaksi_akun_byStatus($id_transaksi, $i);
                    
                    for ($j=0; $j<count($akun); $j++){
                    $data = array('ID_AKUN'=>$akun[$j],'ID_TRANSAKSI'=>$id_transaksi,
                            'JUMLAH_TRANSAKSI'=>$jumlah[$j],'STATUS_NOTE'=>$i);
                    
                        $this->transaksi_akun_model->tambah_transaksi_akun($data);
                    }
                }

                redirect('keuangan/transaksi');
            }
        }
		
		public function delete($id) {
			$spt_ids_post_array = split(",", $this->input->post('items'));
			//$this->load->model('pengolahan/data_model');
			//$msg='akun berhasil dihapus';
			foreach ($spt_ids_post_array as $index => $id) {
				if (isset($id) && $id != '') {
					$this->transaksi_keuangan_model->delete($id);
				}//end if
			}//end foreach
			//$this->peserta_model->delete($id);
			//redirect('peserta/peserta');
		}

        // cek validasi setiap input user
        function cek_validasi() {
            $this->load->library('form_validation');
                $config = array(
                    //validasi form akun
                    array('field'=>'dd_transaksi', 'label'=>'Tanggal transaksi', 'rules'=>'required|integer'),
                    array('field'=>'mm_transaksi', 'label'=>'Tanggal transaksi', 'rules'=>'required|integer'),
                    array('field'=>'yy_transaksi', 'label'=>'Tanggal transaksi', 'rules'=>'required|integer'),
                    array('field'=>'keterangan', 'label'=>'Keterangan', 'rules'=>'required'),
                    array('field'=>'akun_debet', 'label'=>'Akun debet', 'rules'=>'callback_cek_dropdown'),
                    array('field'=>'jml_debet[]', 'label'=>'Jumlah debet', 'rules'=>'required|integer'),
                    array('field'=>'akun_kredit', 'label'=>'Akun kredit', 'rules'=>'callback_cek_dropdown'),
                    array('field'=>'jml_kredit[]', 'label'=>'Jumlah kredit', 'rules'=>'required|integer'),
                    array('field'=>'total_debet', 'label'=>'Balance', 'rules'=>'callback_cek_balance'),
                    array('field'=>'total_kredit', 'label'=>'Balance', 'rules'=>''),
                );

                //setting rules
                $this->form_validation->set_rules($config);

		// Setting Error Message
		$this->form_validation->set_message('required', '%s harus diisi!!');
		$this->form_validation->set_message('integer', '%s harus berisi angka !!');
                $this->form_validation->set_message('greater_than', '%s harus lebih besar atau sama dengan 0 !!');

		$this->form_validation->set_error_delimiters('<p class="error">', '</p>');

                return $this->form_validation->run();
        }

        //cek pilihan dropdown sdh bener ap blm
	function cek_dropdown($id_pilihan){
		if($id_pilihan==0){
			$this->form_validation->set_message('cek_dropdown',
                            'Harap memilih salah satu %s');
			return FALSE;
		}else
			return TRUE;
	}

        //cek nilai total keseimbangan nilai debet dan kredit
	function cek_balance($val){
		if($val==0){
			$this->form_validation->set_message('cek_balance',
                            'Harap hitung nilai %s');
			return FALSE;
		}else if ($val != $this->input->post('total_kredit')){
                    $this->form_validation->set_message('cek_balance',
                            'Nilai %s tidak sama');
			return FALSE;
                }else
			return TRUE;
	}

        function getAkun(){
            $options_akun = '';

            $akun = $this->akun_model->get_active_akun();
            foreach ($akun->result() as $row){
                $options_akun.= '<option value="'.$row->ID_AKUN.'" class="dynamic4">'.$row->NAMA_AKUN.'</option>';
            }

            echo $options_akun;
	}

}

/* End of file transaksi.php */
/* Location: ./application/controllers/transaksi.php */